#!/usr/bin/env python
#coding=utf-8

import time
import json
import logging
import datetime
import pandas as pd
from pprint import pprint

# 下载依赖包：
# pip install alibabacloud_ims20190815==3.0.0 -i https://mirrors.aliyun.com/pypi/simple/
from alibabacloud_ims20190815 import models as ims_20190815_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

from core.logger import logger
from common.aliyun.aliyun_client import AliYunClient
from common.utils import CommonTimeUtils

class AliYunRam(object):
    def __init__(self):
        self.aliyun_client = AliYunClient()
        self.aliyun_configs = self.aliyun_client.get_all_config_v2()
        self.endpoint = 'ims.aliyuncs.com'


    def get_user_basic_infos(self, account_name):
        """
        获取用户的基本信息列表
        """
        try:
            client = self.aliyun_client.get_one_client_v2(account_name, self.endpoint)
            list_user_basic_infos_request = ims_20190815_models.ListUserBasicInfosRequest(max_items=1000)
            runtime = util_models.RuntimeOptions()
            response = client.list_user_basic_infos_with_options(list_user_basic_infos_request, runtime)
            user_basic_infos = response.body.user_basic_infos.to_map()['UserBasicInfo']
        except Exception as e:
            message = UtilClient.assert_as_string(e.message)
            logger.error(f"account:{account_name} get user basic infos error=>{message}")
            return False, None

        return True, user_basic_infos
    
    
    def get_user_detail_infos(self, account_name):
        """
        获取用户的详细信息列表
        """
        try:
            client = self.aliyun_client.get_one_client_v2(account_name, self.endpoint)
            list_users_request = ims_20190815_models.ListUsersRequest()
            runtime = util_models.RuntimeOptions()
            response = client.list_users_with_options(list_users_request, runtime)
            
            user_detail_infos = response.body.users.to_map()["User"]
        except Exception as e:
            message = UtilClient.assert_as_string(e.message)
            logger.error(f"account:{account_name} get user basic infos error=>{message}")
            return False, None

        return True, user_detail_infos
    
    
    def get_user_login_info(self, account_name, user_name):
        """
        获取用户的登陆信息
        """
        try:
            login_info = {
                "Status": "",
                "LastLoginTime": "",
                "MFABindRequired": ""
            }
            client = self.aliyun_client.get_one_client_v2(account_name, self.endpoint)
            get_login_profile_request = ims_20190815_models.GetLoginProfileRequest(user_principal_name=user_name)
            runtime = util_models.RuntimeOptions()
            response = client.get_login_profile_with_options(get_login_profile_request, runtime)
            if response.status_code == 200:
                login_info = response.body.login_profile.to_map()
        except Exception as e:
            # message = UtilClient.assert_as_string(e.message)
            # logger.warning(f"{account_name}:{user_name} get user login info error=>{message}")
            return False, login_info

        return True, login_info
    


    def get_user_access_keys(self, account_name, user_name):
        """
        获取用户的key信息
        """
        try:
            client = self.aliyun_client.get_one_client_v2(account_name, self.endpoint)
            list_access_keys_request = ims_20190815_models.ListAccessKeysRequest(user_principal_name=user_name)
            runtime = util_models.RuntimeOptions()
            response = client.list_access_keys_with_options(list_access_keys_request, runtime)
            user_access_keys = response.body.access_keys.to_map()['AccessKey']
        except Exception as e:
            message = UtilClient.assert_as_string(e.message)
            logger.error(f"{account_name}:{user_name} get user access keys error=>{message}")
            return False, None

        return True, user_access_keys




    def get_user_access_key_last_used(self, account_name, user_name, key_id):
        """
        获取用户的key最后使用时间
        """
        try:
            client = self.aliyun_client.get_one_client_v2(account_name, self.endpoint)
            get_access_key_last_used_request = ims_20190815_models.GetAccessKeyLastUsedRequest(user_access_key_id=key_id, user_principal_name=user_name)
            runtime = util_models.RuntimeOptions()
            response = client.get_access_key_last_used_with_options(get_access_key_last_used_request, runtime)
            last_used_date = response.body.access_key_last_used.last_used_date
        except Exception as e:
            message = UtilClient.assert_as_string(e.message)
            logger.error(f"{account_name}:{user_name} get user access keys error=>{message}")
            return False, None

        return True, last_used_date




    def get_user_infos(self):
        user_infos = []
        for aliyun_config in self.aliyun_configs:
            # 获取用户详细信息列表
            aliyun_config
            result, user_tmp_infos = self.get_user_detail_infos(aliyun_config["name"])
            if not result:
                logger.error(f"account:{aliyun_config['name']} get user detail infos failed")
                continue
            
            for user_tmp_info in user_tmp_infos:
                _, login_info = self.get_user_login_info(aliyun_config["name"], user_tmp_info["UserPrincipalName"])
                
                user_data = {
                    "platform": "阿里云",
                    "account_name": aliyun_config["name"],
                    "user_name": user_tmp_info["UserPrincipalName"].split("@")[0],
                    "console_quired":login_info["Status"],
                    "loast_login": login_info.get("LastLoginTime", ""),
                    "mfa_quired": login_info["MFABindRequired"],
                    "common": user_tmp_info["Comments"],
                    "key1_id": "",
                    "key1_status": "",
                    "key1_create_date": "",
                    "key1_last_date": "",
                    "key2_id": "",
                    "key2_status": "",
                    "key2_create_date": "",
                    "key2_last_date": ""
                }
                
                # 获取用户key信息列表
                result, user_access_keys = self.get_user_access_keys(aliyun_config["name"], user_tmp_info["UserPrincipalName"])
                if not result:
                    logger.error(f"user:{user_tmp_info['UserPrincipalName']} get user access keys failed")
                    continue

                    
                if len(user_access_keys) > 0:
                    user_data["key1_id"] = user_access_keys[0]["AccessKeyId"]
                    user_data["key1_status"] = user_access_keys[0]["Status"]
                    user_data["key1_create_date"] = user_access_keys[0]["CreateDate"]
                    _, user_data["key1_last_date"] = self.get_user_access_key_last_used(aliyun_config["name"], user_tmp_info["UserPrincipalName"], user_access_keys[0]["AccessKeyId"])
                
                if len(user_access_keys) > 1:
                    user_data["key2_id"] = user_access_keys[1]["AccessKeyId"]
                    user_data["key2_status"] = user_access_keys[1]["Status"]
                    user_data["key2_create_date"] = user_access_keys[1]["CreateDate"]
                    _, user_data["key2_last_date"] = self.get_user_access_key_last_used(aliyun_config["name"], user_tmp_info["UserPrincipalName"], user_access_keys[1]["AccessKeyId"])

                user_infos.append(user_data)
                
        return user_infos
            
            
            
    def get_user_infos_to_excel(self):
        user_infos = self.get_user_infos()
        excel_writer = pd.ExcelWriter(f"子账号梳理信息.xlsx")
        df_user_infos = pd.DataFrame(user_infos)
        df_user_infos.to_excel(excel_writer, sheet_name="阿里云", index=False)
        excel_writer.close()
        


def main():
    aliyun_ram = AliYunRam()
    # aliyun_ram.get_user_basic_infos("welabconsfin")
    # aliyun_ram.get_user_detail_infos("welabconsfin")
    # aliyun_ram.get_user_login_info("welabconsfin", "mingzhong.huang@welabconsfin.onaliyun.com")
    # aliyun_ram.get_user_access_keys("welabconsfin", "oss-welab-fund@welabconsfin.onaliyun.com")
    # aliyun_ram.get_user_access_key_last_used("welabconsfin", "oss-welab-fund@welabconsfin.onaliyun.com", "LTAI5tP6tYErB7Em3rvHAKA3")
    # user_infos = aliyun_ram.get_user_infos()
    aliyun_ram.get_user_infos_to_excel()
    print("hello")

    return True



if __name__ == "__main__":
    main()
